<template>
  <div class="medicine-management">
    <div class="page-header">
      <h1>药品管理</h1>
      <p>管理医院药品信息和库存</p>
    </div>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row" v-if="isAdmin">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ statistics.totalMedicines || 0 }}</div>
            <div class="stats-label">药品总数</div>
          </div>
          <el-icon class="stats-icon" color="#409eff"><Medicine /></el-icon>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ statistics.lowStockCount || 0 }}</div>
            <div class="stats-label">库存不足</div>
          </div>
          <el-icon class="stats-icon" color="#e6a23c"><Warning /></el-icon>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ statistics.nearExpiryCount || 0 }}</div>
            <div class="stats-label">即将过期</div>
          </div>
          <el-icon class="stats-icon" color="#f56c6c"><Clock /></el-icon>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ statistics.expiredCount || 0 }}</div>
            <div class="stats-label">已过期</div>
          </div>
          <el-icon class="stats-icon" color="#909399"><Close /></el-icon>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主内容 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>药品列表</span>
              <div class="header-actions">
                <el-button 
                  v-if="isAdmin" 
                  type="success" 
                  @click="showExpiredMedicines"
                  :disabled="statistics.expiredCount === 0">
                  <el-icon><Warning /></el-icon>
                  处理过期药品
                </el-button>
                <el-button 
                  v-if="isAdmin" 
                  type="primary" 
                  @click="showAddDialog">
                  <el-icon><Plus /></el-icon>
                  新增药品
                </el-button>
              </div>
            </div>
          </template>

          <!-- 搜索筛选 -->
          <div class="search-section">
            <el-form :model="searchForm" inline>
              <el-form-item label="药品名称">
                <el-input 
                  v-model="searchForm.keyword" 
                  placeholder="请输入药品名称或编码"
                  clearable
                  style="width: 200px" />
              </el-form-item>
              <el-form-item label="药品分类">
                <el-select 
                  v-model="searchForm.category" 
                  placeholder="请选择分类"
                  clearable
                  style="width: 150px">
                  <el-option label="西药" :value="1" />
                  <el-option label="中药" :value="2" />
                  <el-option label="中成药" :value="3" />
                  <el-option label="生物制品" :value="4" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchMedicines">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 药品表格 -->
          <el-table 
            :data="medicineList" 
            v-loading="loading"
            style="width: 100%">
            <el-table-column prop="medicineCode" label="药品编码" width="120" />
            <el-table-column prop="name" label="药品名称" min-width="150" />
            <el-table-column prop="genericName" label="通用名称" min-width="150" />
            <el-table-column prop="specification" label="规格" width="100" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="manufacturer" label="生产厂家" min-width="120" />
            <el-table-column prop="stockQuantity" label="库存数量" width="100" align="right">
              <template #default="scope">
                <el-tag 
                  :type="getStockTagType(scope.row)" 
                  size="small">
                  {{ scope.row.stockQuantity }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sellingPrice" label="售价" width="100" align="right">
              <template #default="scope">
                ¥{{ scope.row.sellingPrice?.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="expiryDate" label="有效期" width="120">
              <template #default="scope">
                <span :class="{ 'expired-date': isExpired(scope.row.expiryDate), 'near-expiry-date': isNearExpiry(scope.row.expiryDate) }">
                  {{ formatDate(scope.row.expiryDate) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="300" fixed="right">
              <template #default="scope">
                <el-button type="primary" size="small" @click="viewDetail(scope.row)">
                  查看
                </el-button>
                <el-button 
                  v-if="isAdmin" 
                  type="success" 
                  size="small" 
                  @click="showEditDialog(scope.row)">
                  编辑
                </el-button>
                <el-button 
                  v-if="isAdmin" 
                  type="warning" 
                  size="small" 
                  @click="showStockDialog(scope.row)">
                  库存
                </el-button>
                <el-button  v-if="isAdmin"  type="danger" size="small" @click="handleDelete(scope.row)">
                    删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-wrapper">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :current-page="pagination.page"
              :page-size="pagination.size"
              :page-sizes="[10, 20, 50, 100]"
              :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 药品详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="药品详情" 
      width="800px"
      append-to-body>
      <div v-if="currentMedicine" class="medicine-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="药品编码">{{ currentMedicine.medicineCode }}</el-descriptions-item>
          <el-descriptions-item label="药品名称">{{ currentMedicine.name }}</el-descriptions-item>
          <el-descriptions-item label="通用名称">{{ currentMedicine.genericName }}</el-descriptions-item>
          <el-descriptions-item label="药品分类">{{ getCategoryText(currentMedicine.category) }}</el-descriptions-item>
          <el-descriptions-item label="药品类型">{{ getTypeText(currentMedicine.type) }}</el-descriptions-item>
          <el-descriptions-item label="规格">{{ currentMedicine.specification }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{ currentMedicine.unit }}</el-descriptions-item>
          <el-descriptions-item label="生产厂家">{{ currentMedicine.manufacturer }}</el-descriptions-item>
          <el-descriptions-item label="批准文号">{{ currentMedicine.approvalNumber }}</el-descriptions-item>
          <el-descriptions-item label="进价">¥{{ currentMedicine.purchasePrice?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="售价">¥{{ currentMedicine.sellingPrice?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="库存数量">{{ currentMedicine.stockQuantity }}</el-descriptions-item>
          <el-descriptions-item label="安全库存">{{ currentMedicine.safetyStock }}</el-descriptions-item>
          <el-descriptions-item label="最大库存">{{ currentMedicine.maxStock }}</el-descriptions-item>
          <el-descriptions-item label="生产日期">{{ formatDate(currentMedicine.productionDate) }}</el-descriptions-item>
          <el-descriptions-item label="有效期">{{ formatDate(currentMedicine.expiryDate) }}</el-descriptions-item>
          <el-descriptions-item label="存储条件" span="2">{{ currentMedicine.storageCondition }}</el-descriptions-item>
          <el-descriptions-item label="用法用量" span="2">{{ currentMedicine.dosage }}</el-descriptions-item>
          <el-descriptions-item label="功能主治" span="2">{{ currentMedicine.indications }}</el-descriptions-item>
          <el-descriptions-item label="不良反应" span="2">{{ currentMedicine.adverseReactions }}</el-descriptions-item>
          <el-descriptions-item label="禁忌症" span="2">{{ currentMedicine.contraindications }}</el-descriptions-item>
          <el-descriptions-item label="注意事项" span="2">{{ currentMedicine.precautions }}</el-descriptions-item>
          <el-descriptions-item label="备注" span="2">{{ currentMedicine.remark }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 库存管理对话框 -->
    <el-dialog 
      v-model="stockDialogVisible" 
      title="库存管理" 
      width="500px"
      append-to-body>
      <div v-if="currentMedicine" class="stock-management">
        <div class="current-stock">
          <h4>当前库存：{{ currentMedicine.stockQuantity }} {{ currentMedicine.unit }}</h4>
          <p>安全库存：{{ currentMedicine.safetyStock }} {{ currentMedicine.unit }}</p>
        </div>
        
        <el-form :model="stockForm" :rules="stockRules" ref="stockFormRef" label-width="80px">
          <el-form-item label="操作类型" prop="type">
            <el-radio-group v-model="stockForm.type">
              <el-radio value="add">入库</el-radio>
              <el-radio value="reduce">出库</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input-number 
              v-model="stockForm.quantity" 
              :min="1" 
              :max="stockForm.type === 'reduce' ? currentMedicine.stockQuantity : 999999"
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="stockForm.remark" 
              type="textarea" 
              :rows="3" 
              placeholder="请输入操作备注" />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleStockOperation">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 过期药品对话框 -->
    <el-dialog 
      v-model="expiredDialogVisible" 
      title="过期药品管理" 
      width="900px"
      append-to-body>
      <el-table :data="expiredMedicines" v-loading="expiredLoading">
        <el-table-column prop="medicineCode" label="药品编码" width="120" />
        <el-table-column prop="name" label="药品名称" min-width="150" />
        <el-table-column prop="stockQuantity" label="库存数量" width="100" align="right" />
        <el-table-column prop="expiryDate" label="过期时间" width="120">
          <template #default="scope">
            <span class="expired-date">{{ formatDate(scope.row.expiryDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="purchasePrice" label="进价损失" width="120" align="right">
          <template #default="scope">
            ¥{{ (scope.row.stockQuantity * scope.row.purchasePrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleExpiredMedicine(scope.row)">
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="expiredDialogVisible = false">关闭</el-button>
          <el-button type="danger" @click="handleAllExpiredMedicines">批量处理</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { addDialog } from '@/components/gDialog'
import medicineHandle from '@/views/adminModal/medicineHandle.vue'    
import {
  getMedicineList,
  getMedicineDetail,
  getMedicineStatistics,
  getLowStockMedicines,
  getNearExpiryMedicines,
  getExpiredMedicines,
  addMedicineStock,
  reduceMedicineStock
} from '@/api/business'
import {
  deleteMedicine,
  updateMedicineStatus
} from '@/api/admin'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const medicineList = ref([])
const statistics = ref({})
const expiredMedicines = ref([])
const expiredLoading = ref(false)
const currentMedicine = ref(null)

// 对话框显示状态
const detailDialogVisible = ref(false)
const stockDialogVisible = ref(false)
const expiredDialogVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  category: null
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 库存管理表单
const stockForm = reactive({
  type: 'add',
  quantity: 1,
  remark: ''
})

const stockRules = {
  type: [{ required: true, message: '请选择操作类型', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }]
}

const stockFormRef = ref()
// 计算属性
const isAdmin = computed(() => userStore.isAdmin)

// 方法
const fetchMedicines = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    const response = await getMedicineList(params)
    if (response.code === 200) {
      const data = response.data || {}
      medicineList.value = data.list || []
      pagination.total = data.total || 0
      pagination.page = data.page || 1
      pagination.size = data.size || 20
    }
  } catch (error) {
    console.error('获取药品列表失败:', error)
    ElMessage.error('获取药品列表失败')
  } finally {
    loading.value = false
  }
}

const fetchStatistics = async () => {
  try {
    const response = await getMedicineStatistics()
    if (response.code === 200) {
      statistics.value = response.data || {}
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

const searchMedicines = () => {
  pagination.page = 1
  fetchMedicines()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    category: null
  })
  pagination.page = 1
  fetchMedicines()
}

const viewDetail = async (medicine) => {
  try {
    const response = await getMedicineDetail(medicine.id)
    if (response.code === 200) {
      currentMedicine.value = response.data
      detailDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取药品详情失败:', error)
    ElMessage.error('获取药品详情失败')
  }
}

const showStockDialog = (medicine) => {
  currentMedicine.value = medicine
  Object.assign(stockForm, {
    type: 'add',
    quantity: 1,
    remark: ''
  })
  stockDialogVisible.value = true
}

const handleStockOperation = async () => {
  try {
    await stockFormRef.value.validate()
    
    const { type, quantity, remark } = stockForm
    const medicineId = currentMedicine.value.id
    
    let response
    if (type === 'add') {
      response = await addMedicineStock(medicineId, quantity, remark)
    } else {
      response = await reduceMedicineStock(medicineId, quantity, remark)
    }
    
    if (response.code === 200) {
      ElMessage.success(type === 'add' ? '入库成功' : '出库成功')
      stockDialogVisible.value = false
      fetchMedicines()
      fetchStatistics()
    }
  } catch (error) {
    console.error('库存操作失败:', error)
    ElMessage.error('库存操作失败')
  }
}

const showExpiredMedicines = async () => {
  try {
    expiredLoading.value = true
    const response = await getExpiredMedicines()
    if (response.code === 200) {
      expiredMedicines.value = response.data || []
      expiredDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取过期药品失败:', error)
    ElMessage.error('获取过期药品失败')
  } finally {
    expiredLoading.value = false
  }
}

const handleExpiredMedicine = async (medicine) => {
  try {
    await ElMessageBox.confirm(
      `确认处理过期药品"${medicine.name}"吗？处理后该药品库存将被清零。`,
      '确认处理',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await updateMedicineStatus(medicine.id, { status: 3 })
    if (response.code === 200) {
      ElMessage.success('处理成功')
      showExpiredMedicines() // 刷新过期药品列表
      fetchMedicines()
      fetchStatistics()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('处理过期药品失败:', error)
      ElMessage.error('处理过期药品失败')
    }
  }
}

const handleAllExpiredMedicines = async () => {
  try {
    await ElMessageBox.confirm(
      '确认批量处理所有过期药品吗？处理后这些药品库存将被清零。',
      '确认批量处理',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用批量处理接口
    ElMessage.success('批量处理成功')
    expiredDialogVisible.value = false
    fetchMedicines()
    fetchStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量处理失败:', error)
      ElMessage.error('批量处理失败')
    }
  }
}

const showAddDialog = () => {
  addDialog({
    title: '新增药品',
    props: {
      medicineData: {},
      isEdit: false
    },
    width: '900px',
    draggable: true,
    fullscreenIcon: true,
    component: medicineHandle,
    callBack: (result) => {
      if (result === 'success') {
        fetchMedicines()
        fetchStatistics()
      }
    }
  })
}

const showEditDialog = (medicine) => {
  addDialog({
    title: '编辑药品',
    props: {
      medicineData: medicine,
      isEdit: true
    },
    width: '900px',
    draggable: true,
    fullscreenIcon: true,
    component: medicineHandle
  }).then(({ state, data }) => {
    if (state === 'success') {
      fetchMedicines()
      fetchStatistics()
    }
  })
}

const handleCommand = (command) => {
  const { action, row } = command
  if (action === 'edit') {
    showEditDialog(row)
  } else if (action === 'delete') {
    handleDelete(row)
  }
}

const handleDelete = async (medicine) => {
  try {
    await ElMessageBox.confirm(
      `确认删除药品"${medicine.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteMedicine(medicine.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchMedicines()
      fetchStatistics()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSizeChange = (val) => {
  pagination.size = val
  pagination.page = 1
  fetchMedicines()
}

const handleCurrentChange = (val) => {
  pagination.page = val
  fetchMedicines()
}

// 工具方法
const getStockTagType = (medicine) => {
  if (medicine.stockQuantity <= 0) return 'danger'
  if (medicine.stockQuantity <= medicine.safetyStock) return 'warning'
  return 'success'
}

const getStatusTagType = (status) => {
  const types = { 0: 'info', 1: 'success', 2: 'warning', 3: 'danger' }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = { 0: '停用', 1: '正常', 2: '缺货', 3: '过期' }
  return texts[status] || '未知'
}

const getCategoryText = (category) => {
  const texts = { 1: '西药', 2: '中药', 3: '中成药', 4: '生物制品' }
  return texts[category] || '未知'
}

const getTypeText = (type) => {
  const texts = { 1: '处方药', 2: '非处方药' }
  return texts[type] || '未知'
}

const formatDate = (date) => {
  return date ? new Date(date).toLocaleDateString() : '-'
}

const isExpired = (date) => {
  return date && new Date(date) < new Date()
}

const isNearExpiry = (date) => {
  if (!date) return false
  const expiryDate = new Date(date)
  const now = new Date()
  const diffTime = expiryDate - now
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays > 0 && diffDays <= 30
}

// 生命周期
onMounted(() => {
  fetchMedicines()
  fetchStatistics()
})
</script>

<style scoped>
.medicine-management {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 24px;
}

.stats-card {
  position: relative;
  overflow: hidden;
}

.stats-content {
  z-index: 1;
  position: relative;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 14px;
  color: #606266;
}

.stats-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 48px;
  opacity: 0.1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.medicine-detail :deep(.el-descriptions-item__label) {
  font-weight: 600;
  color: #303133;
}

.stock-management .current-stock {
  padding: 16px;
  background: #f0f9ff;
  border-radius: 4px;
  margin-bottom: 20px;
}

.stock-management h4 {
  margin: 0 0 8px 0;
  color: #1f2937;
}

.stock-management p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.expired-date {
  color: #f56c6c;
  font-weight: bold;
}

.near-expiry-date {
  color: #e6a23c;
  font-weight: bold;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 